/**
 * 用户状态管理
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2025-01-30 - 简化登录流程，移除复杂的权限获取逻辑
 */
import { defineStore } from 'pinia'
import { ref, computed, watch, nextTick } from 'vue'
import { login, getUserInfo, logout, refreshToken, type LoginRequest, type UserInfo, type LoginResponse } from '@/api/user'
import router from '@/router'
import { usePermissionStore } from '@/store/permission'
import { STATUS } from '@/constants/enums'
import type { PropertyInfo } from '@/types/property'
import { ROLE_CODES } from '@/constants/roles'

export const useUserStore = defineStore('user', () => {
    // 状态
    const token = ref(localStorage.getItem('token') || '')
    const refreshTokenValue = ref(localStorage.getItem('refreshToken') || '')
    const userInfo = ref<UserInfo | null>(null)
    const isLogged = ref(!!token.value)
    const tokenExpireTime = ref<number>(0)
    const loginTime = ref<number>(0)
    const lastActiveTime = ref<number>(0)
    const isLoggingOut = ref(false)
    const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)
    const userDataScope = ref<{
        isSuperAdmin: boolean
        hasPropertyCompany: boolean
        companyId: number | null
        companyName: string
        companyCode: string
        dataScopeLevel: number
    }>({
        isSuperAdmin: false,
        hasPropertyCompany: false,
        companyId: null,
        companyName: '',
        companyCode: '',
        dataScopeLevel: 0
    })

    // 公司信息相关状态 - 支持多物业公司关联
    const hasCompany = ref<boolean | null>(null)
    const companyList = ref<Array<{
        id: number
        name: string
        code: string
        position?: string
        department?: string
        employeeNo?: string
        joinDate?: string
        status: number
    }>>([])
    const currentCompanyId = ref<number>(0) // 当前选中的物业公司ID
    const currentCompanyName = ref<string>('')
    const currentCompanyCode = ref<string>('')

    // 兼容旧版本的单个物业公司信息（用于向后兼容）
    const companyId = computed(() => currentCompanyId.value)
    const companyName = computed(() => currentCompanyName.value)
    const companyCode = computed(() => currentCompanyCode.value)

    // 计算属性 - Pinia 2.1.7 增强的响应式支持
    const userName = computed(() => userInfo.value?.nickname || userInfo.value?.username || '')
    const userAvatar = computed(() => userInfo.value?.avatar || '')
    const userRoles = computed(() => userInfo.value?.roles || [])
    const userPermissions = computed(() => userInfo.value?.permissions || [])
    const isTokenExpired = computed(() => {
        return tokenExpireTime.value > 0 && Date.now() > tokenExpireTime.value
    })
    const isTokenExpiringSoon = computed(() => {
        // Token在5分钟内过期
        return tokenExpireTime.value > 0 && (tokenExpireTime.value - Date.now()) < 5 * 60 * 1000
    })
    const userType = computed(() => userInfo.value?.userType || 'resident')
    const userStatus = computed(() => userInfo.value?.status || 0)
    const isUserActive = computed(() => userStatus.value === STATUS.DISABLED)

    /**
     * 用户登录 - 简化版本
     * @param loginData 登录数据
     */
    const userLogin = async (loginData: LoginRequest) => {
        try {
            console.log('开始登录，登录数据:', loginData)
            const response = await login(loginData)
            console.log('登录响应:', response)

            // 兼容后端token字段名
            const data: any = response.data
            const accessToken = (data.token || data.accessToken || '') as string
            const newRefreshToken = (data.refreshToken || '') as string
            const expireIn = (data.expireIn || 0) as number
            const userId = (data.userId || data.id || 0) as number
            const username = data.username || ''
            const nickname = data.nickname || data.realName || ''
            const avatar = data.avatar || ''
            const roles = data.roles || []
            // permissions兼容menuPermissions
            const permissions = data.permissions || data.menuPermissions || []
            const propertyCompanyId = data.propertyCompanyId || ''

            console.log('登录响应数据解析:', {
                propertyCompanyId,
                propertyCompanyIdType: typeof propertyCompanyId,
                hasPropertyCompanyId: !!propertyCompanyId,
                hasPropertyCompanyFixed: propertyCompanyId && propertyCompanyId !== '' && propertyCompanyId !== '0',
                roles,
                isSuperAdmin: roles.includes(ROLE_CODES.SUPER_ADMIN)
            })

            // 保存token和refreshToken
            token.value = accessToken
            refreshTokenValue.value = newRefreshToken

            // 计算token过期时间
            tokenExpireTime.value = expireIn > 0 ? Date.now() + (expireIn * 1000) : 0
            loginTime.value = Date.now()
            lastActiveTime.value = Date.now()

            // 保存到localStorage
            if (accessToken) {
                localStorage.setItem('token', accessToken)
            }
            if (newRefreshToken) {
                localStorage.setItem('refreshToken', newRefreshToken)
            } else {
                localStorage.removeItem('refreshToken')
            }
            localStorage.setItem('tokenExpireTime', tokenExpireTime.value.toString())
            localStorage.setItem('loginTime', loginTime.value.toString())

            // 构建用户信息
            const user: UserInfo = {
                id: Number(userId),
                username,
                nickname,
                avatar,
                status: 0,
                createTime: new Date().toISOString(),
                updateTime: new Date().toISOString(),
                roles: roles || [],
                permissions: permissions || [],
                propertyCompanyId: propertyCompanyId
            }

            // 保存用户信息
            userInfo.value = user
            localStorage.setItem('userInfo', JSON.stringify(user))

            // 设置数据权限范围 - 根据权威文档修正
            if (roles.includes(ROLE_CODES.SUPER_ADMIN)) {
                userDataScope.value = {
                    isSuperAdmin: true,
                    hasPropertyCompany: true,  // 超级管理员拥有物业公司权限
                    companyId: null,
                    companyName: '',
                    companyCode: '',
                    dataScopeLevel: 0
                }
            } else {
                // 非超级管理员，检查是否有物业公司关联
                // 修复：正确处理空字符串的情况
                const hasPropertyCompany = propertyCompanyId && propertyCompanyId !== '' && propertyCompanyId !== '0'
                userDataScope.value = {
                    isSuperAdmin: false,
                    hasPropertyCompany: hasPropertyCompany,
                    companyId: hasPropertyCompany ? Number(propertyCompanyId) : null,
                    companyName: '',
                    companyCode: '',
                    dataScopeLevel: hasPropertyCompany ? 1 : 0
                }
            }

            // 更新登录状态
            isLogged.value = true

            // 如果选择记住密码，保存登录信息
            if (loginData.rememberMe) {
                localStorage.setItem('rememberedUsername', loginData.username)
            } else {
                localStorage.removeItem('rememberedUsername')
            }

            // 启动Token自动刷新
            startTokenAutoRefresh()

            // 设置axios默认请求头
            const axios = (await import('axios')).default
            axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`

                // 登录成功后检查并初始化公司信息
    try {
        await checkAndUpdateCompanyInfo()
        console.log('登录后公司信息初始化成功')
    } catch (companyError) {
        console.warn('登录后初始化公司信息失败，但不影响登录:', companyError)
    }

    /**
     * 更新用户信息
     * @param newUserInfo 新的用户信息
     */
    const updateUserInfo = (newUserInfo: UserInfo) => {
        userInfo.value = { ...userInfo.value, ...newUserInfo }
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }

            // 初始化权限数据
            try {
                const permissionStore = usePermissionStore()
                permissionStore.initPermissionsFromUserInfo()
                console.log('登录后权限数据初始化成功')
            } catch (permissionError) {
                console.warn('登录后初始化权限数据失败，但不影响登录:', permissionError)
            }

            console.log('登录成功，用户信息:', user)
            console.log('登录状态:', isLogged.value)
            console.log('Token:', token.value)

            return response
        } catch (error: any) {
            console.error('登录失败:', error)
            throw error
        }
    }

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
        try {
            if (!token.value) {
                throw new Error('未登录')
            }

            const response = await getUserInfo()
            userInfo.value = response.data
            // 健壮性处理，保证permissions和roles为数组
            if (!Array.isArray(userInfo.value.permissions)) {
                userInfo.value.permissions = []
            }
            if (!Array.isArray(userInfo.value.roles)) {
                userInfo.value.roles = []
            }
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

            // 更新最后活跃时间
            lastActiveTime.value = Date.now()

            return response.data
        } catch (error: any) {
            console.error('获取用户信息失败:', error)
            // 如果获取用户信息失败，可能token已过期，执行登出
            await userLogout()
            throw error
        }
    }

    /**
     * 刷新Token
     */
    const refreshUserToken = async () => {
        try {
            if (!refreshTokenValue.value) {
                throw new Error('无刷新令牌')
            }

            const response = await refreshToken(refreshTokenValue.value)
            const { accessToken, refreshToken: newRefreshToken, expireIn } = response.data as any

            // 更新token
            token.value = accessToken
            refreshTokenValue.value = newRefreshToken

            // 更新localStorage
            localStorage.setItem('token', accessToken)
            localStorage.setItem('refreshToken', newRefreshToken)

            // 重新计算过期时间
            tokenExpireTime.value = expireIn > 0 ? Date.now() + (expireIn * 1000) : 0
            localStorage.setItem('tokenExpireTime', tokenExpireTime.value.toString())

            console.log('Token刷新成功')
            return accessToken
        } catch (error: any) {
            console.error('Token刷新失败:', error)
            // Token刷新失败，执行登出
            await userLogout()
            throw error
        }
    }

    /**
     * 用户登出
     */
    const userLogout = async () => {
        if (isLoggingOut.value) {
            return
        }

        try {
            isLoggingOut.value = true
            console.log('开始用户登出')

            // 停止Token自动刷新
            stopTokenAutoRefresh()

            // 调用后端登出接口
            if (token.value) {
                try {
                    await logout()
                } catch (error) {
                    console.warn('后端登出接口调用失败:', error)
                }
            }

            // 清除权限store
            const permissionStore = usePermissionStore()
            permissionStore.resetPermissions()

            // 清除用户信息
            userInfo.value = null
            token.value = ''
            refreshTokenValue.value = ''
            isLogged.value = false
            tokenExpireTime.value = 0
            loginTime.value = 0
            lastActiveTime.value = 0

            // 清除localStorage
            localStorage.removeItem('token')
            localStorage.removeItem('refreshToken')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('tokenExpireTime')
            localStorage.removeItem('loginTime')
            localStorage.removeItem('menuPermissions')

            // 清除公司信息
            clearCompanyInfo()

            // 清除axios默认请求头
            const axios = (await import('axios')).default
            delete axios.defaults.headers.common['Authorization']

            console.log('用户登出完成')
        } catch (error) {
            console.error('用户登出失败:', error)
        } finally {
            isLoggingOut.value = false
        }
    }

    /**
     * 启动Token自动刷新
     */
    const startTokenAutoRefresh = () => {
        stopTokenAutoRefresh()

        if (!token.value || !refreshTokenValue.value) {
            return
        }

        // 每5分钟检查一次Token是否需要刷新
        autoRefreshTimer.value = setInterval(async () => {
            try {
                if (isTokenExpiringSoon.value) {
                    console.log('Token即将过期，开始刷新')
                    await refreshUserToken()
                }
            } catch (error) {
                console.error('Token自动刷新失败:', error)
                // 刷新失败，执行登出
                await userLogout()
            }
        }, 5 * 60 * 1000) // 5分钟

        console.log('Token自动刷新已启动')
    }

    /**
     * 停止Token自动刷新
     */
    const stopTokenAutoRefresh = () => {
        if (autoRefreshTimer.value) {
            clearInterval(autoRefreshTimer.value)
            autoRefreshTimer.value = null
            console.log('Token自动刷新已停止')
        }
    }

    /**
     * 检查权限
     */
    const hasPermission = (permission: string): boolean => {
        // 超级管理员拥有所有权限
        if (userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)) {
            return true
        }

        return userPermissions.value.includes(permission)
    }

    /**
     * 检查角色
     */
    const hasRole = (role: string): boolean => {
        return userRoles.value.includes(role)
    }

    /**
     * 检查是否为管理员
     */
    const isAdmin = (): boolean => {
        return userRoles.value.includes(ROLE_CODES.SUPER_ADMIN) || userRoles.value.includes(ROLE_CODES.ADMIN)
    }

    /**
     * 检查是否为超级管理员
     */
    const isSuperAdmin = (): boolean => {
        console.log('检查超级管理员权限:', {
            userRoles: userRoles.value,
            superAdminCode: ROLE_CODES.SUPER_ADMIN,
            includes: userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)
        })
        return userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)
    }

    /**
     * 初始化用户信息 - 修复版本
     */
    const initUserInfo = async (): Promise<boolean> => {
        console.log('开始初始化用户信息...')
        
        const savedUserInfo = localStorage.getItem('userInfo')
        const savedTokenExpireTime = localStorage.getItem('tokenExpireTime')
        const savedLoginTime = localStorage.getItem('loginTime')

        // 同步加载所有状态
        if (savedUserInfo) {
            try {
                userInfo.value = JSON.parse(savedUserInfo)
                console.log('从localStorage恢复用户信息成功')
            } catch (error) {
                console.error('解析用户信息失败:', error)
                localStorage.removeItem('userInfo')
                userInfo.value = null
            }
        }

        if (savedTokenExpireTime) {
            tokenExpireTime.value = parseInt(savedTokenExpireTime)
        }

        if (savedLoginTime) {
            loginTime.value = parseInt(savedLoginTime)
        }

        // 确保状态一致性
        const hasValidToken = !!token.value && !isTokenExpired.value
        const hasValidUserInfo = !!userInfo.value
        
        isLogged.value = hasValidToken && hasValidUserInfo
        
        console.log('初始化用户信息完成:', {
            hasToken: !!token.value,
            tokenExpired: isTokenExpired.value,
            hasUserInfo: hasValidUserInfo,
            isLogged: isLogged.value
        })

        // 检查token是否过期 - 简化检查，不自动刷新
        if (isTokenExpired.value) {
            console.log('Token已过期，清除登录状态')
            // Token过期，清除登录状态
            isLogged.value = false
            userInfo.value = null
            localStorage.removeItem('userInfo')
            return false
        } else if (token.value && userInfo.value) {
            // Token有效且有用户信息，启动自动刷新
            startTokenAutoRefresh()
            return true
        }
        
        return false
    }

    // 公司信息相关方法
    const initCompanyInfo = async () => {
        console.log('开始初始化公司信息...')
        const savedCompanyInfo = localStorage.getItem('companyInfo')
        if (savedCompanyInfo) {
            try {
                const companyData = JSON.parse(savedCompanyInfo)
                hasCompany.value = companyData.hasCompany
                companyList.value = companyData.companyList || []
                currentCompanyId.value = companyData.currentCompanyId || 0
                currentCompanyName.value = companyData.currentCompanyName || ''
                currentCompanyCode.value = companyData.currentCompanyCode || ''
                console.log('从localStorage恢复公司信息:', companyData)
            } catch (error) {
                console.error('解析公司信息失败:', error)
                localStorage.removeItem('companyInfo')
                // 解析失败时，调用API重新获取
                await checkAndUpdateCompanyInfo()
            }
        } else {
            console.log('localStorage中没有公司信息，调用API检查')
            // localStorage中没有数据，调用API检查
            await checkAndUpdateCompanyInfo()
        }
    }

    const updateCompanyInfo = (companyData: PropertyInfo) => {
        hasCompany.value = true
        companyList.value.push({
            id: companyData.propertyCompanyId || 0,
            name: companyData.companyName || '',
            code: companyData.companyCode || '',
            status: 1 // 假设所有新增的物业公司都是有效的
        })
        currentCompanyId.value = companyData.propertyCompanyId || 0
        currentCompanyName.value = companyData.companyName || ''
        currentCompanyCode.value = companyData.companyCode || ''

        // 保存到localStorage
        localStorage.setItem('companyInfo', JSON.stringify({
            hasCompany: true,
            companyList: companyList.value,
            currentCompanyId: currentCompanyId.value,
            currentCompanyName: currentCompanyName.value,
            currentCompanyCode: currentCompanyCode.value
        }))
    }

    const clearCompanyInfo = () => {
        hasCompany.value = null
        companyList.value = []
        currentCompanyId.value = 0
        currentCompanyName.value = ''
        currentCompanyCode.value = ''
        localStorage.removeItem('companyInfo')
    }

    // 新增：切换当前物业公司
    const switchCurrentCompany = (companyId: number) => {
        const company = companyList.value.find(c => c.id === companyId)
        if (company) {
            currentCompanyId.value = company.id
            currentCompanyName.value = company.name
            currentCompanyCode.value = company.code
            
            // 更新localStorage
            localStorage.setItem('companyInfo', JSON.stringify({
                hasCompany: true,
                companyList: companyList.value,
                currentCompanyId: currentCompanyId.value,
                currentCompanyName: currentCompanyName.value,
                currentCompanyCode: currentCompanyCode.value
            }))
            
            console.log('切换当前物业公司:', company)
        }
    }

    // 新增：获取用户关联的所有物业公司
    const getUserPropertyCompanies = async () => {
        try {
            const { propertyInfoApi } = await import('@/api/property/propertyInfo')
            // 传入当前用户ID
            const currentUserId = userInfo.value?.id
            if (!currentUserId) {
                console.error('用户信息不存在，无法获取物业公司列表')
                return
            }
            const res = await propertyInfoApi.getUserPropertyCompanies(currentUserId)
            if (res.code === 200 && res.data) {
                companyList.value = res.data.map((company: any) => ({
                    id: company.propertyCompanyId,
                    name: company.propertyCompanyName,
                    code: company.propertyCompanyCode || company.propertyCompanyName,
                    position: company.position,
                    department: company.department,
                    employeeNo: company.employeeNo,
                    joinDate: company.joinDate,
                    status: company.status
                }))
                
                // 只有在当前没有选中物业公司时，才设置第一个为默认
                if (currentCompanyId.value === 0 && companyList.value.length > 0) {
                    switchCurrentCompany(companyList.value[0].id)
                }
                
                hasCompany.value = companyList.value.length > 0
                
                // 更新localStorage
                localStorage.setItem('companyInfo', JSON.stringify({
                    hasCompany: hasCompany.value,
                    companyList: companyList.value,
                    currentCompanyId: currentCompanyId.value,
                    currentCompanyName: currentCompanyName.value,
                    currentCompanyCode: currentCompanyCode.value
                }))
                
                console.log('获取用户物业公司列表成功:', companyList.value)
            }
        } catch (error) {
            console.error('获取用户物业公司列表失败:', error)
        }
    }

    // 新增：检查用户是否关联指定物业公司
    const hasPropertyCompany = (companyId: number): boolean => {
        return companyList.value.some(company => company.id === companyId && company.status === 1)
    }

    // 新增：获取当前物业公司信息
    const getCurrentCompany = () => {
        return companyList.value.find(company => company.id === currentCompanyId.value)
    }

    const checkAndUpdateCompanyInfo = async () => {
        try {
            // 根据权威文档实现：调用API获取公司信息
            if (hasCompany.value !== null) {
                console.log('公司信息已初始化，跳过API调用')
                return
            }
            
            console.log('首次检查用户是否关联物业公司')
            const { propertyInfoApi } = await import('@/api/property/propertyInfo')
            const res = await propertyInfoApi.hasPropertyCompany()
            hasCompany.value = !!res.data
            
            if (hasCompany.value) {
                console.log('用户关联物业公司，获取详细信息')
                // 获取用户关联的所有物业公司
                await getUserPropertyCompanies()
                
                // 如果当前没有选中的物业公司，才设置第一个为默认
                if (currentCompanyId.value === 0 && companyList.value.length > 0) {
                    switchCurrentCompany(companyList.value[0].id)
                }
            } else {
                console.log('用户未关联物业公司')
                companyList.value = []
                currentCompanyId.value = 0
                currentCompanyName.value = ''
                currentCompanyCode.value = ''
                
                // 保存到localStorage
                localStorage.setItem('companyInfo', JSON.stringify({
                    hasCompany: false,
                    companyList: [],
                    currentCompanyId: 0,
                    currentCompanyName: '',
                    currentCompanyCode: ''
                }))
            }
            
            console.log('公司信息检查完成:', {
                hasCompany: hasCompany.value,
                companyList: companyList.value,
                currentCompanyId: currentCompanyId.value
            })
        } catch (error) {
            console.error('检查公司信息失败:', error)
            hasCompany.value = false
        }
    }

    const checkUserHasPropertyCompany = (): boolean => {
        return hasCompany.value === true
    }

    const checkDataPermission = (level: number): boolean => {
        if (userDataScope.value.isSuperAdmin) {
            return true
        }
        return userDataScope.value.dataScopeLevel >= level
    }

    const getUserDataScope = () => {
        return userDataScope.value
    }

    const hasPropertyCompanyPermission = (): boolean => {
        // 根据权威文档实现：使用hasCompany变量进行权限判断
        const isSuper = isSuperAdmin()
        
        console.log('物业公司权限检查:', {
            isSuperAdmin: isSuper,
            hasCompany: hasCompany.value,
            companyId: currentCompanyId.value,
            userRoles: userRoles.value,
            userDataScope: userDataScope.value
        })
        
        // 超级管理员或有物业公司关联的用户都有权限
        const hasPermission = isSuper || hasCompany.value === true
        console.log('物业公司权限检查结果:', hasPermission)
        return hasPermission
    }

    const hasCommunityPermission = (): boolean => {
        return userDataScope.value.dataScopeLevel >= 1 || userDataScope.value.isSuperAdmin
    }

    // 检查是否有任意权限
    const hasAnyPermission = (permissions: string[]): boolean => {
        return permissions.some(permission => hasPermission(permission))
    }

    // 检查是否有所有权限
    const hasAllPermissions = (permissions: string[]): boolean => {
        return permissions.every(permission => hasPermission(permission))
    }

    // 更新用户信息
    const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
        if (userInfo.value) {
            userInfo.value = { ...userInfo.value, ...newUserInfo }
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        }
    }

    // 获取记住的用户名
    const getRememberedUsername = (): string => {
        return localStorage.getItem('rememberedUsername') || ''
    }

    // 检查Token有效性
    const checkTokenValidity = (): boolean => {
        if (!token.value) {
            return false
        }

        // 只检查是否过期，不进行自动刷新
        if (isTokenExpired.value) {
            console.log('Token已过期')
            return false
        }

        return true
    }

    // 更新最后活跃时间
    const updateLastActiveTime = () => {
        lastActiveTime.value = Date.now()
    }

    // 获取用户会话时长（分钟）
    const getSessionDuration = (): number => {
        if (!loginTime.value) {
            return 0
        }
        return Math.floor((Date.now() - loginTime.value) / (1000 * 60))
    }

    // 监听Token变化，自动启动/停止刷新
    watch(token, (newToken) => {
        if (newToken) {
            startTokenAutoRefresh()
        } else {
            stopTokenAutoRefresh()
        }
    })

    // 初始化
    if (token.value) {
        initUserInfo().then(success => {
            if (success) {
                // 异步初始化公司信息，但不阻塞store初始化
                initCompanyInfo().catch(error => {
                    console.warn('初始化公司信息失败，但不影响store初始化:', error)
                })
            }
        })
    }

    return {
        // 状态
        token,
        refreshTokenValue,
        userInfo,
        isLogged,
        tokenExpireTime,
        loginTime,
        lastActiveTime,
        isLoggingOut,
        userDataScope,

        // 公司信息状态
        hasCompany,
        companyList,
        currentCompanyId,
        currentCompanyName,
        currentCompanyCode,

        // 计算属性
        userName,
        userAvatar,
        userRoles,
        userPermissions,
        isTokenExpired,
        isTokenExpiringSoon,
        userType,
        userStatus,
        isUserActive,

        // 方法
        login: userLogin,
        logout: userLogout,
        userLogout: userLogout,
        getUserInfo: fetchUserInfo,
        refreshToken: refreshUserToken,
        hasPermission,
        hasRole,
        isAdmin,
        hasAnyPermission,
        hasAllPermissions,
        updateUserInfo,
        initUserInfo,
        getRememberedUsername,
        checkTokenValidity,
        updateLastActiveTime,
        getSessionDuration,
        startTokenAutoRefresh,
        stopTokenAutoRefresh,
        initCompanyInfo,
        updateCompanyInfo,
        clearCompanyInfo,
        checkAndUpdateCompanyInfo,
        isSuperAdmin,
        checkUserHasPropertyCompany,
        checkDataPermission,
        getUserDataScope,
        hasPropertyCompanyPermission,
        hasCommunityPermission,
        switchCurrentCompany,
        getUserPropertyCompanies,
        hasPropertyCompany,
        getCurrentCompany
    }
})
